package com.jm.api;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jm.common.conf.api.ApiResult;
import com.jm.common.tool.exception.ErrorException;
import com.jm.constant.SysApiConstant;
import com.jm.model.SysUser;
import com.jm.service.i.SysUserService;
import com.jm.service.impl.TestDsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author kong
 */
@Tag(name = "开放的登录接口")
@RestController
@RequestMapping(SysApiConstant.OPEN_API)
public class LoginApi {
    private final SysUserService sysUserService;
    private final TestDsService testDsService;

    @Autowired
    public LoginApi(SysUserService sysUserService, TestDsService testDsService) {
        this.sysUserService = sysUserService;
        this.testDsService = testDsService;
    }

    @GetMapping("/test/{id}")
    @ApiResult
    public SysUser test(@PathVariable("id") Long id) {
        return this.sysUserService.get(id);
    }


    @Operation(summary = "登录")
    @Parameters({@Parameter(name = "username", description = "账号", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "password", description = "密码", required = true, in = ParameterIn.QUERY)})
    @PostMapping("/login/sys")
    @ApiResult
    public String login(String username, String password) {
//        this.testDsService.test();

        SysUser sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username).last("limit 1"));

        if (new BCryptPasswordEncoder().matches(password, sysUser.getPassword())) {
            // 登录
            StpUtil.login(UUID.randomUUID());
            return StpUtil.getTokenValue();
        }
        throw new ErrorException("登录失败");
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
    }
}
